package ferp.android.tasks.center;

import android.os.AsyncTask;
import ferp.center.client.Action;
import ferp.center.network.request.RequestBidAdd;
import ferp.core.ai.nn.Adaptation;
import ferp.core.game.Bid;
import ferp.core.game.Game;
import ferp.core.game.Statistics;
import ferp.core.log.Log;
import ferp.core.player.Player;
import ferp.core.player.Profile;

/**
 * User: igorgok
 * Date: 12/5/12 5:36 PM
 */
public class TaskBidAdd extends AsyncTask<Void, Void, Void>
{
  public TaskBidAdd(Profile profile, Game game)
  {
    this.profile = profile;
    this.game = game;
    // game bid (may change in the game object, so we keep it separately)
    this.gameCurrentBid = game.bid;
  }

  @Override
  protected Void doInBackground(Void... voids)
  {
    try
    {
      RequestBidAdd request = new RequestBidAdd();
      Player human = game.human();
      Statistics statistics = profile.getStatistics();

      // determine human hand
      int hand = 0;

      for (Player p = game.starting(); p != human; p = game.next(p))
        ++hand;

      // fill up request data
      request.profile = profile.centerId;
      request.configuration = profile.getConfiguration();
      request.hand = hand;
      request.cards = game.getHumanHand().initial;
      request.penalty = Adaptation.getPenalty(game, profile.settings);
      request.result = RequestBidAdd.type(game.getHumanBid().current.type);
      request.last = (hand == 0 ? RequestBidAdd.NONE : (gameCurrentBid == null ? RequestBidAdd.PASS : RequestBidAdd.type(gameCurrentBid.type)));
      request.starting = game.getStartingTricks(profile.settings);
      request.pool = statistics.totalPool;
      request.score = statistics.totalAmount;

      // send
      Action.execute(Action.BID_ADD, request, Boolean.class);
    }
    catch (Exception e)
    {
      Log.error(Action.TAG, e);
    }

    return null;
  }

  private final Profile profile;
  private final Game game;
  private final Bid gameCurrentBid;
}
